package com.smart.advice;

import com.google.common.collect.Lists;
import com.smart.common.WebResponse;
import com.smart.common.exception.BusinessException;
import com.smart.common.exception.BusinessNotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author zhanghong
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class ControllerAdvice {

    @ExceptionHandler({BusinessNotLoginException.class})
    public WebResponse handleBusinessNotLoginException(BusinessException ex) {
        log.error("Got BusinessException [{}]", ex.getMessage(), ex);
        return new WebResponse(ex.getErrorCode().getCode(), ex.getErrorCode().getMsg());
    }

    @ExceptionHandler({BusinessException.class})
    public WebResponse handleBusinessException(BusinessException ex) {
        log.error("Got BusinessException [{}]", ex.getMessage(), ex);
        return new WebResponse(ex.getErrorCode().getCode(), StringUtils.isNotBlank(ex.getMessage()) ? ex.getMessage() : ex.getErrorCode().getMsg());
    }

    @ExceptionHandler({Exception.class})
    public WebResponse handleException(Exception ex) {
        log.error("Go unhandled exception: ", ex);
        return new WebResponse("" + HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
    }

    @ExceptionHandler({RuntimeException.class})
    public WebResponse handleRuntimeException(RuntimeException ex) {
        log.error("Got RuntimeException [{}] ", ex.getMessage(), ex);
        return new WebResponse("" + HttpStatus.BAD_REQUEST.value(), ex.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public WebResponse handleArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("Go MethodArgumentNotValidException: ", ex);
        List<ObjectError> objectErrors = Optional.ofNullable(ex.getBindingResult()).map(Errors::getAllErrors).orElse(Lists.newArrayList());
        String errorMsg = objectErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";\n"));
        return new WebResponse("" + HttpStatus.INTERNAL_SERVER_ERROR, errorMsg);
    }
}
